package com.lazy.es.es_demo.search;



import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.search.SearchType;
import org.elasticsearch.client.Client;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import static org.elasticsearch.index.query.QueryBuilders.*;

/**
 * unitest demo
 * @author luodan
 *
 */
public class SearchTest1 {
    private static Logger logger = LoggerFactory.getLogger(SearchTest1.class);
    private SearchDemo demo;
    
    private Client initGetClient() {
        demo = new SearchDemo("my-es");
        demo.addTransportAddress("192.168.1.60", 9300);
        return demo.getClient();
    }

    private void closeClient() {
        if (demo != null) {
            demo.destroy();
        }
    }

    @Test
    public void getOne() {
        Client client = initGetClient();
        GetResponse response = client.prepareGet("twitter", "tweet", "1")
                .setOperationThreaded(false)
                .get();
        logger.info("result = {}", response.getSourceAsString());
        closeClient();
    }
    
    @Test
    public void getMulti() {
        Client client = initGetClient();
        SearchResponse response = client.prepareSearch("twitter")
                .setTypes("tweet")
                .setSearchType(SearchType.DFS_QUERY_THEN_FETCH)
                .setQuery(QueryBuilders.termQuery("user", "kimchy"))                 // Query
                //.setPostFilter(QueryBuilders.rangeQuery("_id").from("12").to("1800"))      // Filter
                .setFrom(0).setSize(6).setExplain(true)
                .execute()
                .actionGet();
                
        logger.info("result = {}", response);
        closeClient();
    }
    
}
